package com.czk.practice.codec;

import com.czk.practice.domain.Packet;
import com.czk.util.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/19 15:11
 */
public class Encoder extends MessageToByteEncoder<Packet> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Packet packet, ByteBuf byteBuf) throws Exception {
        // 序列化内容
        byte[] bytes = SerializationUtil.serializer(packet);
        // 添加长度存储对应字节码的序号
        byteBuf.writeInt(bytes.length + 1);
        byteBuf.writeByte(packet.getCommand());
        byteBuf.writeBytes(bytes);
    }
}
